// pages/profile/index.ts
const app = getApp()

Page({
  data: {
    avatar: '',
    nickName: ''
  },
  onLoad () {
    const { nickName, avatar } = app
    this.setData({ nickName, avatar })
  },
  //修改用户名
  async updateNickname (ev) {
    const nickName = ev.detail.value
    if (nickName === '') return
    const { code, message, data } = await wx.http.put('/userInfo', { nickName })
    console.log(data)
    if (code !== 10000) return wx.utils.toast()
    wx.utils.toast(message)
    this.setData({ nickName })
    app.getUserInfo('nickName', nickName)
  },
  //更换头像
  updateAvatar (ev) {
    // console.log(ev)
    wx.uploadFile({
      filePath: ev.detail.avatarUrl,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: `Bearer ${app.token}`
      },
      formData: { type: 'avatar' },
      success: ({ data }) => {
        const res = JSON.parse(data)
        // 检测接口是否调用成功
        if (res.code !== 10000) return wx.utils.toast('上传头像失败!')
        console.log(res)

        this.setData({ avatar: res.data.url })

        // app.getUserInfo('avatar', res.data.url)
      }
    })
  }
})
